package vn.edu.hungvuongaptech.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.edu.hungvuongaptech.common.Constant;
import vn.edu.hungvuongaptech.dao.TimeSheetDAO;

/**
 *
 * @author Leung
 * Export selected timesheet to xml format
 */
public class ExportTimeSheetController extends HttpServlet {

    private static final int BUFFER = 4096;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String[] chkTimeSheetIDs = request.getParameterValues("chkTimeSheetID");
        // validate
        if (chkTimeSheetIDs == null || chkTimeSheetIDs.length < 0) {
            String errorPage = Constant.PATH_RES.getString("timesheet.admin.messagePath") + "?msg=Please select Timesheet's records to export!";
            response.sendRedirect(response.encodeRedirectURL(errorPage));
            return;
        }
        // re-edit ids for a proper format
        String ids = Arrays.toString(chkTimeSheetIDs);
        ids = ids.substring(1, ids.length() - 2);

        InputStream xml = TimeSheetDAO.exportXML(ids);
        byte[] outByte = new byte[BUFFER];
        // generate file name
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy_HHmmss");
        String today = formatter.format(date);
        String fileName = String.format("Timesheet" + today + ".zip");

        response.setContentType("Application/x-download");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(out);
        try {
            // start compress data
            ZipEntry entry = new ZipEntry("TimeSheet.xml");
            zos.putNextEntry(entry);
            int bytes;
            while ((bytes = xml.read(outByte, 0, BUFFER)) != -1) {
                zos.write(outByte, 0, bytes);
            }
            zos.closeEntry();
            zos.finish();
        } finally {
            //out.flush();
            out.flush();
            xml.close();
            out.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
